/*
 * @(#)BookmarkUtil.java $version 2012. 4. 18.
 *
 * Copyright 2007 NHN Corp. All rights Reserved. 
 * NHN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

package com.design.oop.util;

import java.util.Set;
import java.util.TreeSet;

import android.content.Context;
import android.content.SharedPreferences;

import com.design.oop.bean.WheatBeerKind;

public class BookmarkPreference {
	public static final String PREF_CONFIG_KEY = "wheatbeer_config_pref";
	public static final String PREF_BOOKMARK = "bookmark";

	public static Set<Integer> getBookmarkList(Context context) {
		SharedPreferences pref = context.getSharedPreferences(PREF_CONFIG_KEY, Context.MODE_PRIVATE);
		String bookmarkStr = pref.getString(PREF_BOOKMARK, null);
		if (StringUtils.isEmpty(bookmarkStr)) {
			return null;
		}

		String[] bookmarkArray = bookmarkStr.split("[,]");
		if (bookmarkArray == null || bookmarkArray.length == 0) {
			return null;
		}

		Set<Integer> bookmarkSet = new TreeSet<Integer>();
		for (String bookmark : bookmarkArray) {
			bookmarkSet.add(Integer.parseInt(bookmark));
		}

		return bookmarkSet;
	}

	public static void addBookmark(Context context, int id) {
		Set<Integer> bookmarkSet = getBookmarkList(context);
		if (CommonUtil.isEmptySet(bookmarkSet)) {
			bookmarkSet = new TreeSet<Integer>();
		}

		int index = WheatBeerKind.getIndexByDrawableId(id);
		bookmarkSet.add(index);

		setBookmark(context, bookmarkSet);
	}

	public static void removeBookmark(Context context, int id) {
		Set<Integer> bookmarkSet = getBookmarkList(context);
		if (CommonUtil.isEmptySet(bookmarkSet)) {
			return;
		}

		int index = WheatBeerKind.getIndexByDrawableId(id);
		bookmarkSet.remove(index);

		setBookmark(context, bookmarkSet);
	}

	private static void setBookmark(Context context, Set<Integer> bookmarkSet) {
		String bookmarkStr = "";
		for (Integer bookmark : bookmarkSet) {
			bookmarkStr = bookmarkStr.concat(Integer.toString(bookmark));
			bookmarkStr = bookmarkStr.concat(",");
		}

		SharedPreferences pref = context.getSharedPreferences(PREF_CONFIG_KEY, Context.MODE_PRIVATE);
		SharedPreferences.Editor editor = pref.edit();
		editor.putString(PREF_BOOKMARK, bookmarkStr);
		editor.commit();
	}
}
